package com.haiheng.voiceandbook.service

import android.Manifest
import android.R
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import com.haiheng.library.log.LogUtils
import com.haiheng.library.log.LogWriter
import com.haiheng.voiceandbook.Constants
import com.haiheng.voiceandbook.commo.VersionManager


/**
 *
 * @Des:
 * @Author: hwz
 * @Date:2023/10/9 0009
 * @Version: 1.0
 */


class RestartService : Service() {
    private val handler = Handler()
    private val RESTART_DELAY: Long = 5000 // 5秒
    private var time :Long = 0;

    private val restartRunnable: Runnable = object : Runnable {
        override fun run() {
            Log.d(TAG, "检查是否在前台运行:${Constants.isAppInForeground()}")

            if (!Constants.isAppInForeground() && Constants.isExitOpenApp()) {
                LogWriter.d(TAG+ "App is not running, restarting...")
                startApp()
            } else {
//                LogUtils.d(TAG+ "App is already running")
                if (System.currentTimeMillis() - time > 1000*60*10 && requestPermissions1()){
                    time = System.currentTimeMillis()
                    LogWriter.d(TAG+ "App is already running getVersionInfo")
                    VersionManager.getVersionInfo(applicationContext,false)
                }

            }
            handler.postDelayed(this, RESTART_DELAY)
        }
    }
    override fun onCreate() {
        super.onCreate()
        try {
            LogWriter.d(TAG+ "RestartService onCreate")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val notificationManager: NotificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
                // 创建一个新的通知渠道
                val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT)
                notificationManager.createNotificationChannel(channel)
            }
            time = System.currentTimeMillis()
            handler.postDelayed(restartRunnable, RESTART_DELAY)
        }catch (ex:Exception){
            LogWriter.e(TAG+"${ex}")
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "RestartService onDestroy")
        handler.removeCallbacks(restartRunnable)

    }
    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        try {
            LogWriter.d(TAG+ "RestartService started")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val notification = NotificationCompat.Builder(this, CHANNEL_ID)
                    .setContentTitle("Restart Service Notification")
                    .setContentText("This is a notification from my Restart service.")
                    .build()
                startForeground(1, notification)
            }
        }catch (ec:Exception){
            LogWriter.e(TAG+"${ec}")
        }


        return START_STICKY
    }


    private fun startApp() {
        // 重新启动应用
        try {
            val launchIntent = packageManager.getLaunchIntentForPackage(packageName)
            launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            launchIntent?.let { startActivity(it) }
        }catch (ex:Exception){
            LogWriter.e(TAG+"重新启动异常${ex}")
        }
    }

    companion object {
        private const val TAG = "RestartService"
        private const val CHANNEL_ID = "my_channel_id"
        private const val CHANNEL_NAME = "Channel Name"
        private const val CHANNEL_DESCRIPTION = "Channel Description"
        private const val CHANNEL_IMPORTANCE = NotificationManager.IMPORTANCE_DEFAULT
    }


    fun requestPermissions1():Boolean {
        try {
            if (Build.VERSION.SDK_INT >= 23) {
                val requestPerssionArr = ArrayList<String>()
                val hasSdcardRead = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                if (hasSdcardRead != PackageManager.PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.READ_EXTERNAL_STORAGE)
                }
                val hasSdcardWrite = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                if (hasSdcardWrite != PackageManager.PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                }
                // 是否应该显示权限请求
                if (requestPerssionArr.size >= 1) {
                    val requestArray = arrayOfNulls<String>(requestPerssionArr.size)
                    for (i in requestArray.indices) {
                        requestArray[i] = requestPerssionArr[i]
                    }
                    return false
                }else{
                    return true
                }

            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return false
    }

}
